package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.*;

import com.zhiyun.hxzy.domain.*;
import com.zhiyun.hxzy.domain.Dictionary;
import com.zhiyun.hxzy.domain.queryvo.Result;
import com.zhiyun.hxzy.domain.Student;
import com.zhiyun.hxzy.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;
@Transactional
@Service
public class StudentService {
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private ClassesDao classesDao;
    @Autowired
    private EmploymentService employmentService;
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private SMSUtil2 smsUtil2;
    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private RedisTemplate<Object, Object> template;
    @Autowired
    private HomeWorkDao homeWorkDao;
    @Autowired
    private HomeWorkInstructionDao homeWorkInstructionDao;
    @Autowired
    private DictionaryDao dictionaryDao;
    @Autowired
    private UploadUtil uploadUtil;
    private final String REGISTER_REDIS_KEY = "register_";

    //查询所有学生
    public Page<Student> findAll(int pageNum, int pageSize,Long classId) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        if(classId != null){
            return studentDao.findByClassId(classId,pageRequest);
        }else {
            return studentDao.findAll(pageRequest);
        }
    }

    public List<Student> findAll(Long id) {
        return studentDao.findByClassId(id);
    }

    //根据id查询学生
    public Student getOne(Long id) {
        Student student = null;
        if (id != null) {
            student = studentDao.getOne(id);
        }
        return student;
    }

    //添加学生
    public void addStudent(Student student) {
        if (student != null && !student.equals("")) {
            studentDao.save(student);
        }
    }


    //给学生添加作业
    public void addHomework(Homework homework, Long[] studentIds, Long studentId) {
        homework.setTime(new Date());
        Homework homework2 = homeWorkDao.save(homework);
        HomeWorkInstruction homeWorkInstruction = new HomeWorkInstruction();
        homeWorkInstruction.setInstruction(homework.getInstruction());
        homeWorkInstruction.setHomeworkId(homework2.getId());
        homeWorkInstructionDao.save(homeWorkInstruction);


        if (studentIds == null) {
            Student student = studentDao.getOne(studentId);
            student.getHomeworks().add(homework);
            studentDao.save(student);
        } else {
            for (Long s : studentIds) {
                Student student = studentDao.getOne(s);
                student.getHomeworks().add(homework);
                studentDao.save(student);
            }
        }
    }

    //验证手机号是否被使用
    public Result isUsePhone(String phoneNum){
        Result result = new Result();
        Student student = studentDao.findByPhoneNum(phoneNum);
        if(student != null){
            result.setResult(false);
            result.setMessage("该手机已被注册");
        }else {
            result.setResult(true);
        }
        return result;
    }

    //给手机发送验证码
    public void sendCodeToPhone(String phoneNum){
        String code = codeUtil.getCode();
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        smsUtil2.sendCheckCode(phoneNum, code);
                        template.opsForValue().set(REGISTER_REDIS_KEY + phoneNum,code);//key:手机号,value:验证码
                        template.expire(phoneNum,60*5, TimeUnit.SECONDS);//设置300S过期
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //通过手机号验证
    public Result verifyCode(String phoneNum, String code) {
        Result result = new Result();
        String redisCode = (String) template.opsForValue().get(REGISTER_REDIS_KEY+phoneNum);
        if (code != null && code.contains(redisCode)) {
            result.setResult(true);
        } else {
            result.setResult(false);
            result.setMessage("验证码不一致,请重新进行验证");
        }
        return result;
    }

    //查询同班同学
    public List<Student> addPre(Long studentId) {
        Student student = studentDao.findById(studentId).get();
        Long id = student.getClasses().getId();
        List<Student> students = studentDao.findByClassId(id);
        return students;
    }

    //查询作业内容
    public List<Dictionary> findByContent() {
        List<Dictionary> types = dictionaryDao.findByType("内容");
        return types;
    }

    //查询标签
    public  List<Dictionary> findByTags(){
        List<Dictionary> types = dictionaryDao.findByType("标签");
        return types;
    }

    //登录 给手机发送验证码
    public void loginSendCodeToPhone(String phoneNum){
        String code = codeUtil.getCode();
        try {
            smsUtil2.sendCheckCode(phoneNum, code);
            template.opsForValue().set("login"+phoneNum,code);//key:手机号,value:验证码
            template.expire(phoneNum,60, TimeUnit.SECONDS);//设置60S过期
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //注册第三步:确认用户两次设置的密码是否一致
    public boolean judgePass(String pass1, String pass2) {
        if (pass1.contains(pass2)) {
            return true;
        } else {
            return false;
        }
    }

    //通过手机号和密码查询学生
    public Student findByPhoneNumAndPassword(String phoneNum, String password) throws Exception {
        String passwordNew = Md5Util.encodeByMd5(password);
        Student student = studentDao.findByPhoneNumAndPassword(phoneNum, passwordNew);
        return student;
    }


    //通过手机号查找学生
    public Student findByPhoneNum(String phoneNum) {
        Student student = studentDao.findByPhoneNum(phoneNum);
        return student;
    }

    //登录 给手机发送验证码
    public Result LoginSendPhoneCode(String phoneNum) {
        Student student = studentDao.findByPhoneNum(phoneNum);
        if (student != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String code = codeUtil.getCode();
                    try {
                        smsUtil2.sendCheckCode(phoneNum, code);
                        template.opsForValue().set("login" + phoneNum, code);//key:手机号,value:验证码
                        template.expire(phoneNum, 60*5, TimeUnit.SECONDS);//设置300S过期
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            return new Result("已发送", true);
        } else {
            return new Result("该手机未注册", false);
        }
    }

    //验证码登录
    public Result loginVerifyCode(String phoneNum, String code) {
        Student student = studentDao.findByPhoneNum(phoneNum);
        if (student == null) {
            return new Result("该手机未注册", false);
        } else {
            String redisCode = (String) template.opsForValue().get("login" + phoneNum);
            if (code.contains(redisCode)) {
                return new Result("登陆成功", true);
            } else {
                return new Result("验证码错误", false);
            }
        }
    }

    //学生修改个人信息
    public Student updatePersonalMessage(Student student,Long classId) {
        Student oldStudent = studentDao.getOne(student.getId());
        student.setClasses(classesDao.getOne(classId));
        student.setHomeworks(oldStudent.getHomeworks());
        studentDao.save(student);

        return studentDao.getOne(student.getId());
    }

    //上传头像
    public Result uploadHeaderImg(String file) {
        MultipartFile multipartFile = Base64ToMultipartUtil.base64ToMultipart(file);
        long size = multipartFile.getSize();
        if(size >= 1024*1024){
            return new Result("数据超过1M，请重新上传！",false);
        }
        String path = uploadUtil.upload(multipartFile);
        return new Result(path,true);
    }

    //学生重置密码
    public void resetPassword(String password,String phoneNum) {
        if (phoneNum != null && password != null) {
            String passwordNew = null;
            try {
                passwordNew = Md5Util.encodeByMd5(password);
            } catch (Exception e) {
                e.printStackTrace();
            }
            studentDao.resetPassword(passwordNew,phoneNum);
        }
    }

    //被关注时增加粉丝数量
    public void addFansCount(Long id){
        studentDao.addFans(id);
    }

    //被取消关注时减少粉丝数量
    public void deleteFansCount(Long id){
        studentDao.deleteFans(id);
    }
}
